#include "util.h"

unsigned long stringToUl(char* str){
	int i;
	unsigned long result = 0;
	for(i = 0; i < 4; i++){
		result += str[4-i-1]*((unsigned long) powUl(256,i));
	}
	return result;
}

unsigned stringToU(char* str){
	int i;	
	unsigned result = 0;
	for(i = 0; i < 2; i++){
		result += str[2-i-1]*((unsigned) powU(256,i));
	}
	return result;
}

unsigned long powUl(unsigned long x, unsigned long y){
	unsigned long i, result = 1;
	for(i = 0; i < y; i++){
		result *= x;
	}
	return result;
}

unsigned powU(unsigned x, unsigned y){
	unsigned i, result = 1;
	for(i = 0; i < y; i++){
		result *= x;
	}
	return result;
}

char* uToString(unsigned x){
	char * result = (char*) malloc (3);
	result[2] = '\0';
	result[1] = x % 256;
	result[0] = (x - result[1]) / 256;
	return result;
}

char* ulToString(unsigned long x){
	char * result = (char*) malloc (5);
	result[4] = '\0';
	int i;
	for(i = 3; i>=0; i--){
		if(i==3)
			result[i] = x % 256;
		else
			result[i] = x;
		x = (x - result[i]) / 256;
	}
	return result;
}


char *ilanginAt(const char*pstr){
	return substr(pstr,1,strlen(pstr)-1);
}

char *ilanginMountPoint(const char* mpoint, const char* dirpath){
	return substr(dirpath,strlen(mpoint),strlen(dirpath)-strlen(mpoint));
}

char *substr(const char *pstr, int start, int numchars)
{
	char *pnew = malloc(numchars+1);
	strncpy(pnew, pstr + start, numchars);
	pnew[numchars] = '\0';
	return pnew;
}
